<template>
  <div class="container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="订单编号">
        <el-input v-model="formInline.out_trade_no" placeholder="请输入订单编号" clearable />
      </el-form-item>
      <el-form-item label="下单时间">
        <datePickerRange v-model:start="formInline.beginTime" v-model:end="formInline.endTime">
        </datePickerRange>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="init">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="formInline.status" type="card" @tab-click="handleClick">
      <el-tab-pane :label="item.name" :name="item.value" v-for="(item,index) in counter.orderStatus" :key="index"></el-tab-pane>
    </el-tabs>

    <el-table :data="tableParmas.rows">
      <el-table-column prop="out_trade_no" label="订单编号" min-width="150" align="center" />
      <el-table-column label="用户昵称">
        <template #default="scope">
          {{scope.row.user.nickname}}
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="详情" min-width="150" align="center">
        <template #default="scope">
          <el-button type="primary" text @click="open(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="送达时间" min-width="160" align="center">
        <template #default="scope">
          {{scope.row.data.time}}
        </template>
      </el-table-column>
      <el-table-column prop="total" label="总价" />
      <el-table-column label="状态" min-width="150" align="center">
        <template #default="scope">
          <el-tag v-if="['success','delivery'].includes(scope.row.status)">{{counter.status_format(scope.row.status)}}</el-tag>
          <el-tag v-else-if="['cancel','finish','refunded'].includes(scope.row.status)" type="info">{{counter.status_format(scope.row.status)}}</el-tag>
          <el-tag v-else-if="['refund'].includes(scope.row.status)" type="danger">{{counter.status_format(scope.row.status)}}</el-tag>
          <el-tag v-else type="warning">{{counter.status_format(scope.row.status)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" min-width="150" align="center">
        <template #default="scope">
          {{proxy.$utils.dateTimeFormateFn(scope.row._add_time,"all")}}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template #default="scope">
          <el-button type="primary" v-if="scope.row.status=='refund'" text @click="handle(scope.row,1)">确认退款</el-button>
          <el-button type="primary" v-if="scope.row.status=='success'" text @click="handle(scope.row,2)">拣货完成</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="tableParmas['total']" :total="tableParmas['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <el-dialog v-model="dialogVisible" title="购买详情" width="60%" :before-close="handleClose">
      <el-table :data="row.products">
        <el-table-column prop="date" label="商品图">
          <template #default="scope">
            <el-image style="width: 100px; height: 100px" :src="productImage_format(scope.row.productImage)" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" />
        <el-table-column prop="num" label="购买数量" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="price" label="总价">
          <template #default="scope">
            {{scope.row.num*scope.row.price}}
          </template>
        </el-table-column>
      </el-table>
      <el-descriptions title="下单详情" border class="descriptionsLabel120" :column="2">
        <el-descriptions-item label="订购人电话">{{row.data.mobile}}</el-descriptions-item>
        <el-descriptions-item label="祝福语">{{row.data.blessings}}</el-descriptions-item>
        <el-descriptions-item label="备注">{{row.data.remark}}</el-descriptions-item>
        <el-descriptions-item label="送达时间">
          {{row.data.time}}
        </el-descriptions-item>
        <el-descriptions-item label="收货地址">{{address_format(row.data.addressId)}}</el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="支付详情" v-if="row.pay_amount" border class="descriptionsLabel120" :column="2">
        <el-descriptions-item label="支付金额">￥{{row.pay_amount.total/100}}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{proxy.$utils.dateTimeFormateFn(row.pay_time,"all")}}</el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="退货详情" v-if="row.refund" border class="descriptionsLabel120" :column="2">
        <el-descriptions-item label="联系号码">{{row.refund.mobile}}</el-descriptions-item>
        <el-descriptions-item label="备注">{{row.refund.remark}}</el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="退款详情" v-if="row.refund_amount" border class="descriptionsLabel120" :column="2">
        <el-descriptions-item label="退款金额">￥{{row.refund_amount.refund/100}}</el-descriptions-item>
        <el-descriptions-item label="退款时间">{{proxy.$utils.dateTimeFormateFn(row.refund_time,"all")}}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleClose">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="show" title="确认退款" width="500" :before-close="handleClose">
      <el-form :model="refundModel" class="demo-form-inline">
        <el-form-item label="支付金额">
          {{refundModel.total}}
        </el-form-item>
        <el-form-item label="退款金额">
          <el-input-number v-model="refundModel.refund" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="loading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
import { computed, onMounted } from "vue";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();

let formInline = ref({
  pageIndex: 1,
  pageSize: 10,
  status: "",
  out_trade_no: "", //1707206774266851
  beginTime: "",
  endTime: "",
});
let tableParmas = ref({});
let dialogVisible = ref(false);
let show = ref(false);
let products = ref([]);
let row = ref({});
let address = ref([]);
let refundModel = ref({
  out_trade_no: "",
  refund: null,
  total: null,
});
let loading = ref(false);

onMounted(() => {
  search();
});
let parmas = computed(() => {
  let query = { ...formInline.value };
  if (query.beginTime) {
    query.beginTime = `${query.beginTime} 00:00:00`;
    query.endTime = `${query.endTime} 23:59:00`;
  }
  return query;
});

let search = () => {
  formInline.value.pageIndex = 1;
  getInfo();
};
let init = () => {
  formInline.value = {
    pageIndex: 1,
    pageSize: 10,
    status: "",
    out_trade_no: "", //1707206774266851
    beginTime: "",
    endTime: "",
  };
  getInfo();
};
let getInfo = async () => {
  //await proxy.$apis.changeOrderStatus();
  tableParmas.value = await proxy.$apis.orderList(parmas.value);
  //console.log("订单", tableParmas.value.rows);
};
let handleClick = (e) => {
  formInline.value.status = counter.orderStatus[Number(e.index)].value;
  search();
};
let handleClose = () => {
  refundModel.value = {
    out_trade_no: "",
    refund: null,
    total: null,
  };
  dialogVisible.value = false;
  show.value = false;
};
let open = async (arr) => {
  row.value = proxy.$utils.deepcopy(arr);
  address = await proxy.$apis.receivingAddress({ userId: arr.userId });
  dialogVisible.value = true;
};
let productImage_format = (e) => {
  if (!e) return;
  let arr = e.split(",");
  return arr[0];
};
let address_format = (e) => {
  let index = proxy.$utils.findIndexByField(address, "_id", e);
  let obj = address[index];
  return `${obj.province}${obj.city}${obj.region} ${obj.area}`;
};
let onSubmit = async () => {
  try {
    loading.value = true;
    if (!refundModel.value.refund)
      return proxy.$utils.showToast("请输入退款金额", 0);

    if (refundModel.value.refund > refundModel.value.total)
      return proxy.$utils.showToast("退款金额不可大于支付金额", 0);

    await proxy.$apis.orderRefunds(refundModel.value);
    setTimeout(() => {
      proxy.$utils.showToast("退款成功(状态可能会延迟更新)");
      handleClose();
    }, 1000);
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
let handle = async (item, num) => {
  switch (num) {
    case 1: //确认退款
      let total = item.pay_amount
        ? item.pay_amount.payer_total / 100
        : item.total;
      refundModel.value.total = total;
      refundModel.value.refund = total;
      refundModel.value.out_trade_no = item.out_trade_no;
      row.value = proxy.$utils.deepcopy(item);
      show.value = true;
      break;
    case 2: //拣货完成
      let resp = await proxy.$utils.confirmTips("是否确定拣货完成?");
      if (!resp) return;
      await proxy.$apis.orderList({
        type: "delivery",
        out_trade_no: item.out_trade_no,
      });
      proxy.$utils.showToast("修改状态完成");
      getInfo();
      break;
    default:
      break;
  }
};
</script>



<style lang="scss" scoped>
.container {
  margin: 20px;
  .el-descriptions {
    margin-top: 25px;
  }
}
</style>
